import axios from "axios";
import store from "@/store";

const whiteList = ["/auth/signIn", "/auth/signUp", "/auth/signUp"];

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || "",
  timeout: 6000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8' // chrome(utf-8) is different from firefox(UTF-8)
  }
});

const err = (error) => {
  if (error.response) {
    const data = error.response.data;
    const status = error.response.status;
    switch (status) {
      case 400:
        error.message = "请求错误";
        break;
      case 401:
        error.message = "未授权，请登录";
        break;
      case 403:
        error.message = "拒绝访问";
        break;
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`;
        break;
      case 408:
        error.message = "请求超时";
        break;
      case 500:
        error.message = "服务器内部错误";
        break;
      case 501:
        error.message = "服务未实现";
        break;
      case 502:
        error.message = "网关错误";
        break;
      case 503:
        error.message = "服务不可用";
        break;
      case 504:
        error.message = "网关超时";
        break;
      case 505:
        error.message = "HTTP版本不受支持";
        break;
      default:
        console.log(error.response.status);
    }
    if (status === 403) {
      /*notification.error({
        message: 'Forbidden',
        description: data.message
      })*/
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      /*notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })*/
      const token = store.getters.token;
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
};

service.interceptors.request.use(
  config => {
    console.log('requesting....');
    const token = store.getters.token;
    if (token && !whiteList.includes(config.url)) {
      config.headers["Authorization"] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error)
  }
);

service.interceptors.response.use(
  response => {
    return response.data;
  },
  err
);

export default service;
